import Vue from 'vue'
import Vuex from 'vuex'
import { loginAPI } from '../api/user/index'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: window.localStorage.getItem('tokenStr') || '',
    refresh_token: window.localStorage.getItem('refreshTokenStr') || ''
  },
  mutations: {
    setToken (state, tokenStr) {
      state.token = tokenStr
      localStorage.setItem('token', tokenStr)
    },
    setRefreshToken (state, refreshTokenStr) {
      state.refresh_token = refreshTokenStr
      localStorage.setItem('refresh_token', refreshTokenStr)
    }
  },

  actions: {
    async asyncLoginAction (store, obj) {
      try {
        const res = await loginAPI(obj.username, obj.password)
        const { token, refresh_token: refreshToken } = res.data.data
        store.commit('setToken', token)
        store.commit('setRefreshToken', refreshToken)
        return Promise.resolve(res) // 返回成功的Promise对象
      } catch (err) {
        return Promise.reject(err) // 返回失败的Promise对象
      }
    }
  },
  modules: {
  }
})
